package com.ys.erp.stage_user_service.utils;

import com.alibaba.fastjson2.JSONObject;
import com.ys.erp.common.enums.RedisKey;
import com.ys.erp.framework.exception.YsException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 微信工具类（简化版）
 * @author zjj
 * @date 2025/01/21
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WxUtil {

    @Value("${properties.wx.app-id}")
    private String appId;

    @Value("${properties.wx.app-secret}")
    private String appSecret;

    private final RestTemplate restTemplate;

    private final RedisTemplate<String, String> redisTemplate;

    /**
     * 获取微信access_token
     *
     * @return access_token
     */
    public String getAccessToken() {
        String redisToken = redisTemplate.opsForValue().get(RedisKey.Enums.WX_ACCESS_TOKEN.getKey());
        if (ObjectUtils.isNotEmpty(redisToken)) {
            return redisToken;
        }
        
        String url = "https://api.weixin.qq.com/cgi-bin/token?"
                + "grant_type=client_credential"
                + "&appid=" + appId
                + "&secret=" + appSecret;
                
        String resStr = restTemplate.getForObject(url, String.class);
        JSONObject resJson = JSONObject.parseObject(resStr);
        
        if (ObjectUtils.isEmpty(resJson)) {
            throw new YsException(-1, "请求微信接口错误");
        }
        
        if (!resJson.containsKey("access_token") || ObjectUtils.isEmpty(resJson.get("access_token"))) {
            throw new YsException(-1, "获取微信access_token失败：" + resStr);
        }
        
        String accessToken = resJson.getString("access_token");
        redisTemplate.opsForValue().set(RedisKey.Enums.WX_ACCESS_TOKEN.getKey(), accessToken, 55, TimeUnit.MINUTES);
        
        log.info("成功获取微信access_token");
        return accessToken;
    }
} 